/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.fee.entity.Consignor;
import com.jeeplus.modules.fee.entity.FeeData;
import com.jeeplus.modules.fee.entity.PayTip;
import com.jeeplus.modules.fee.entity.Payable;
import com.jeeplus.modules.fee.service.PayTipService;
import com.jeeplus.modules.fee.service.PayableService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.Date;
import java.util.List;

/**
 * 应付结算单与订单关联Controller
 * @author cyf
 * @version 2017-04-05
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/feePayTip")
public class PayTipController extends BaseController {

	@Autowired
	private PayTipService feePayTipService;
	@Autowired
	private PayableService feePayableService;
	
	@ModelAttribute
	public PayTip get(@RequestParam(required=false) String id) {
		PayTip entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = feePayTipService.get(id);
		}
		if (entity == null){
			entity = new PayTip();
		}
		return entity;
	}
	
	/**
	 * 应付结算单相关订单列表页面
	 */
	@RequiresPermissions("fee:feePayTip:list")
	@RequestMapping(value = {"list", ""})
	public String list(PayTip feePayTip, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<PayTip> page = feePayTipService.findPage(new Page<PayTip>(request, response), feePayTip);
		model.addAttribute("page", page);
		return "modules/fee/feePayTipList";
	}

	/**
	 * 查看，增加，编辑应付结算单相关订单表单页面
	 */
	@RequiresPermissions(value={"fee:feePayTip:view","fee:feePayTip:add","fee:feePayTip:edit"},logical= Logical.OR)
	@RequestMapping(value = "form")
	public String form(PayTip feePayTip, Model model) {
		model.addAttribute("feePayTip", feePayTip);
		return "modules/fee/feePayTipForm";
	}

	/**
	 * 保存应付结算单相关订单
	 */
	@RequiresPermissions(value={"fee:feePayTip:add","fee:feePayTip:edit"},logical= Logical.OR)
	@RequestMapping(value = "save")
	public String save(@RequestParam(value = "dataId")String dataId, @RequestParam(value = "rows")String rows, @RequestParam(value="payMoney")String payMoney,
                       @RequestParam(value = "payUnit")String payUnit, @RequestParam(value = "payRemark")String payRemark, RedirectAttributes redirectAttributes) throws Exception{
		if (StringUtils.isEmpty(dataId) || StringUtils.isEmpty(payUnit) || StringUtils.isEmpty(payMoney)){
			addMessage(redirectAttributes,"数据异常!");
			return "redirect:"+ Global.getAdminPath()+"/fee/feeData/?repage";
		}
		if(StringUtils.isEmpty(rows)){
			addMessage(redirectAttributes,"所选记录行号为空!");
			return "redirect:"+ Global.getAdminPath()+"/fee/feeData/form?id="+dataId;
		}
		Payable feePayable = new Payable();//设置结算单
		feePayable.setStatus(0);
		feePayable.setClearingNo(feePayableService.createPayClearNo());
		feePayable.setBusyDate(new Date());
		Consignor feeConsignor = new Consignor();
		feeConsignor.setId(payUnit);
		feePayable.setPayee(feeConsignor);
		feePayable.setClearingMoney(Double.parseDouble(payMoney));
		feePayable.setRemarks(payRemark);//结算单设置完毕
		FeeData feeData = new FeeData();
		feeData.setId(dataId);//数据源设置完毕
		String[] rowNos = rows.trim().split(",");
		if(rowNos==null || rowNos.length<1){
			addMessage(redirectAttributes,"数据异常!");
			return "redirect:"+ Global.getAdminPath()+"/fee/feeData/form?id="+dataId;
		}
		PayTip feePayTip = null;
		for(int i=0;i<rowNos.length;i++){
			feePayTip = new PayTip();
			feePayTip.setFeePayable(feePayable);
			feePayTip.setFeeData(feeData);
			feePayTip.setRowNo(Integer.parseInt(rowNos[i]));
			feePayTipService.save(feePayTip);//保存结算单与订单的关联表
		}
		addMessage(redirectAttributes, "保存应付结算单相关订单成功");
		return "redirect:"+ Global.getAdminPath()+"/fee/feePayTip/?repage";
	}
	
	/**
	 * 删除应付结算单相关订单
	 */
	@RequiresPermissions("fee:feePayTip:del")
	@RequestMapping(value = "delete")
	public String delete(PayTip feePayTip, RedirectAttributes redirectAttributes) {
		feePayTipService.delete(feePayTip);
		addMessage(redirectAttributes, "删除应付结算单相关订单成功");
		return "redirect:"+ Global.getAdminPath()+"/fee/feePayTip/?repage";
	}
	
	/**
	 * 批量删除应付结算单相关订单
	 */
	@RequiresPermissions("fee:feePayTip:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			feePayTipService.delete(feePayTipService.get(id));
		}
		addMessage(redirectAttributes, "删除应付结算单相关订单成功");
		return "redirect:"+ Global.getAdminPath()+"/fee/feePayTip/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("fee:feePayTip:export")
    @RequestMapping(value = "export", method= RequestMethod.POST)
    public String exportFile(PayTip feePayTip, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "应付结算单相关订单"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<PayTip> page = feePayTipService.findPage(new Page<PayTip>(request, response, -1), feePayTip);
    		new ExportExcel("应付结算单相关订单", PayTip.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出应付结算单相关订单记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+ Global.getAdminPath()+"/fee/feePayTip/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:feePayTip:import")
    @RequestMapping(value = "import", method= RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<PayTip> list = ei.getDataList(PayTip.class);
			for (PayTip feePayTip : list){
				try{
					feePayTipService.save(feePayTip);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条应付结算单相关订单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条应付结算单相关订单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入应付结算单相关订单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+ Global.getAdminPath()+"/fee/feePayTip/?repage";
    }
	
	/**
	 * 下载导入应付结算单相关订单数据模板
	 */
	@RequiresPermissions("fee:feePayTip:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "应付结算单相关订单数据导入模板.xlsx";
    		List<PayTip> list = Lists.newArrayList();
    		new ExportExcel("应付结算单相关订单数据", PayTip.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+ Global.getAdminPath()+"/fee/feePayTip/?repage";
    }
	
	
	

}